package ioc

import (
	"gitee.com/chicken-c/go-learn/webook/internal/web"
	ijwt "gitee.com/chicken-c/go-learn/webook/internal/web/jwt"
	"gitee.com/chicken-c/go-learn/webook/internal/web/middleware"
	"gitee.com/chicken-c/go-learn/webook/pkg/ginx/middleware/accesslog"
	"gitee.com/chicken-c/go-learn/webook/pkg/ginx/middleware/ratelimit"
	"gitee.com/chicken-c/go-learn/webook/pkg/logger"
	ratelimit2 "gitee.com/chicken-c/go-learn/webook/pkg/ratelimit"
	"github.com/gin-contrib/cors"
	"github.com/gin-gonic/gin"
	"github.com/redis/go-redis/v9"
	"strings"
	"time"
)

func InitWebServer(funcs []gin.HandlerFunc,
	userHdl *web.UserHandler, wechatHdl *web.OAuto2WechatHandler,
	artHdl *web.ArticleHandler) *gin.Engine {
	server := gin.Default()
	server.Use(funcs...)
	// 注册路由
	userHdl.RegisterRoutes(server)
	wechatHdl.RegisterRoutes(server)
	artHdl.RegisterRoute(server)
	return server
}

func GinMiddlewares(cmd redis.Cmdable, l logger.Logger, jwtHdl ijwt.Handler) []gin.HandlerFunc {
	return []gin.HandlerFunc{
		//redis限流
		ratelimit.NewBuilder(ratelimit2.NewRateSlideWindowLimit(cmd, 1, 100)).Build(),
		//CORS跨域问题
		CorsHandler(),

		// 登录校验
		middleware.NEWLoginMiddlewareJWTBuilder(cmd, jwtHdl).
			Ignore("/users/signup").
			Ignore("/users/login").
			Ignore("refresh_token").
			Ignore("/users/login_sms/code/send").
			Ignore("/oauth2/wechat/authurl").
			Ignore("/oauth2/wechat/callback").
			Ignore("/users/login_sms").
			LoginCheck(),

		//出入口打印日志
		accesslog.NewBuilder(l).Build(),

		// 使用session 登录校验
		//sessionHandlerFunc(),
		//middleware.NewLoginMiddlewareBuilder().CheckLogin(),
	}
}

func CorsHandler() gin.HandlerFunc {
	return cors.New(cors.Config{
		AllowOrigins:     []string{"http://localhost:3000"},
		AllowMethods:     []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"}, // 允许的 HTTP 方法
		AllowCredentials: true,
		// 在使用 JWT 的时候，因为我们使用了 Authorization 的头部，所以要加上
		AllowHeaders: []string{"Content-Type", "Authorization"},
		// 为了 JWT
		ExposeHeaders: []string{"X-Jwt-Token", "x-refresh-token"},
		AllowOriginFunc: func(origin string) bool {
			if strings.HasPrefix(origin, "http://localhost") {
				return true
			}
			return strings.Contains(origin, "your_company.com")
		},
		MaxAge: 12 * time.Hour,
	})
}
